package aquarium.reseau;

import java.io.*;
import java.net.Socket;
import java.util.Vector;

class Connection extends Thread {

	private InputStreamReader _depuisClient;
	private Socket _client;
	private PrintStream _versClient;
	private String[] _items_base = null;
	private int _id;
	private Vector<String> _collection = new Vector<String>();
	private boolean _changed = false;


	public void start(Socket client, String[] items_base, int id){
		this._client = client;
		this._items_base = items_base;
		this._id = id;

		try {
			// creation des flux de/vers le client
			_depuisClient = new InputStreamReader(_client.getInputStream());
			_versClient = new PrintStream(_client.getOutputStream());

		} catch (IOException e) {
			try { client.close(); } catch (IOException ee) {}
		}
		this.start();
	}


	public void run() {
		BufferedReader buffer = new BufferedReader(_depuisClient);

		String[] tableau = _items_base;
		for(int i = 0 ; i < tableau.length; i++){
			_versClient.println(tableau[i]);
		}

		while (true){

			try {
				while(buffer.ready()){
					decrypt_message(buffer);
					_changed = true;
				}
				Connection.sleep((long) 1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


	/****   Accesseur  ****/

	public int get_id(){
		return _id;
	}

	public boolean has_changed(){
		return _changed;
	}

	public void changed(){
		_changed = false;
		_collection.clear();
	}


	public Vector<String> get_collection(){
		synchronized (_collection){
			Vector<String> tmp = new Vector<String>(_collection);
			_collection.clear();
			return tmp;
		}
	}

	/****   Fonctions  ****/

	public void decrypt_message(BufferedReader buffer){
		String message = new String();
		synchronized (_collection){
			if(has_changed())
				while((message.lastIndexOf("end") == -1)){
					try {
						message = buffer.readLine();
						if(message != null){
							if(message.lastIndexOf("end") == -1){
								_collection.add(message);
							}
						}
					} catch (IOException e) {
						System.out.println("Erreur : buffer.readLine()");
						e.printStackTrace();

					}
				}
		}
	}

	public void send_collection(Vector<String> message, int id){
		int i = 0;
		for(; i<message.size(); i++) {
			_versClient.println(message.get(i));
		}
		if(i == message.size())
			_versClient.println("end " + id);


	}
}
